import React from 'react';
import { Form, Input, Select, Button, Row, Col, Upload, message, Divider, Checkbox, Modal, Space } from 'antd';
import { LoadingOutlined, CloseOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import PswUpdate from './pswUpdate';
import ImgQuick from '@/pages/admin/imgQuick';
import ItemSelect from '@/components/ItemSelect';

const { confirm } = Modal;
class UserEdit extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            imageUrl: '',
            imgList: [],
            disabled: true,
            datas: {},
            Roles: [],
        }
    }
    formRef: any = React.createRef();

    componentDidMount() {
        this.initData();
        this.fetchRoles();
    }
    initData = () => {
        this.getCurrentUser();
    }
    getCurrentUser = () => {
        this.props.dispatch({
            type: "Abp/getCurrentUser",
        }).then(() => {
            this.fetchUser();
        })
    }
    fetchUser = () => {
        const { currentUser } = this.props;
        if (currentUser) {
            this.getUserById(currentUser?.id)
        }
    }
    getUserById = (Id:number)=>{
        this.props.dispatch({
            type: 'Abp/get',
            payload: { Id },
            control: 'User',
        }).then(() => {
            let datas = this.props.response?.result;
            if (datas) {
                this.setState({ imageUrl: datas.avater, datas })
                this.formRef.current.setFieldsValue({ user: datas });
            }
        });
    }
    fetchRoles = () => {
        this.props.dispatch({
            type: "Abp/getAll",
            payload: { SkipCount: 0, MaxResultCount: 100 },
            control: 'Role',
        }).then(() => {
            var resp = this.props.response?.result;
            if (resp) {
                var Roles = this.props.response.result.items;
                this.setState({ Roles })
            }
        });
    }

    onFinish = async (values: any) => {
        this.setState({ loading: true });
        var user = values.user;
        var act = "Abp/update";
        if (user.id == 0 || !user.id) {
            act = "Abp/create";
            user.password = "123456";
        }
        if (this.state.imageUrl) {
            user.avater = this.state.imageUrl;
        }
        this.props.dispatch({
            type: act,
            payload: user,
            control: 'User',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('保存成功！');
            }
            else {
                message.error('保存错误，请联系管理员！');
            }
            this.setState({ loading: false });
        });
    };
    onChange = (value: any) => {
        console.log(value);
    }
    handleChange = (info: any) => {
        if (info.file.status === 'done' && info.file.response) {
            this.setState({
                imageUrl: info.file.response.result
            })
        }
    };
    handleAdd = () => {
        this.setState({ disabled: false, imageUrl: null, imgList: [] });
        this.formRef.current.resetFields();
    }
    handleDel = () => {
        const { datas } = this.state;
        if (datas.userName == "admin") {
            message.error('管理员用户不允许删除！');
        }
        else {
            this.props.dispatch({
                type: "Abp/delete",
                payload: { Id: datas.id },
                control: 'User',
            }).then(() => {
                var resp = this.props.response;
                if (resp.success) {
                    message.success('删除成功！');
                    this.props.refresh();
                    this.formRef.current.resetFields();
                }
                else {
                    message.error('删除错误，请联系管理员！');
                }
            })
        }

    }
    delConfirm = () => {
        var _this = this;
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.handleDel();
            },
            onCancel() { },
        });
    }
    getUserByName = (item: any) => {
        if (item) {
            this.getUserById(item?.id)
            //if (item.avater)
            //     this.setState({ imageUrl: item.avater });
            // this.formRef.current.setFieldsValue({ user: item });
        }
    }
    switchModal = (visible: boolean) => {
        this.setState({ visible });
    }
    clickFun = (val: any) => {
        this.setState({
            imageUrl: val,
            visible: false
        })
    }
    render() {
        const layout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 10 },
        };
        const { imageUrl, loading, Roles, datas } = this.state;
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const columns = [
            {
                title: '用户名',
                dataIndex: 'userName',
            },
            {
                title: '姓名',
                dataIndex: 'fullName',
            },
        ]
        return (
            <div>
                <Space>
                    <Button type="primary" icon={<PlusOutlined />} onClick={this.handleAdd}>新增</Button>
                    <Button type="primary" icon={<CloseOutlined />} onClick={this.delConfirm}>删除</Button>
                    <Button type="primary" onClick={() => this.switchModal(true)}>更改密码</Button>
                </Space>
                <Divider />
                <Row gutter={16}>
                    <Col span={16}>
                        <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                            <Form.Item
                                label="用户名">
                                <Input.Group compact>
                                    <Form.Item
                                        name={['user', 'userName']}
                                        noStyle
                                        rules={[{ required: true, message: "请输入用户名" }]}>
                                        <Input style={{ width: 100 }} />
                                    </Form.Item>
                                    <Form.Item noStyle>
                                        <ItemSelect
                                            width={500}
                                            control='User'
                                            columns={columns}
                                            text="选择"
                                            title="选择用户"
                                            act="GetLists"                                            
                                            setCurrent={this.getUserByName} />
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>
                            <Form.Item name={['user', 'id']} style={{ display: 'none' }}>
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'avater']} style={{ display: 'none' }}>
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name={['user', 'empID']}
                                label="员工工号"
                                rules={[{ required: true, message: "请输入或选择员工" }]}>
                                <Input style={{ width: '50%' }} />
                            </Form.Item>
                            <Form.Item label="姓名">
                                <Input.Group compact>
                                    <Form.Item
                                        noStyle
                                        name={['user', 'name']}
                                        rules={[{ required: true, message: "请输入姓" }]} >
                                        <Input style={{ width: '50%' }} placeholder="姓" />
                                    </Form.Item>
                                    <Form.Item
                                        noStyle
                                        name={['user', 'surname']}
                                        rules={[{ required: true, message: "请输入名" }]}>
                                        <Input style={{ width: '50%' }} placeholder="名" />
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>

                            <Form.Item
                                name={['user', 'fullName']}
                                label="员工姓名"
                                rules={[{ required: true, message: "请输入员工姓名" }]}>
                                <Input style={{ width: '50%' }} />
                            </Form.Item>
                            <Form.Item
                                name={['user', 'address']}
                                label="联系地址">
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'telphone']} label="联系电话">
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'emailAddress']}
                                rules={[{ required: true, message: "请输入电子邮件" }]}
                                label="电子邮件">
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'roleNames']} label="系统角色">
                                <Select mode="multiple">
                                    {
                                        Roles.map((item: any) => {
                                            return (
                                                <Select.Option
                                                    key={item.id}
                                                    value={item.normalizedName}>{item.displayName}
                                                </Select.Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item name={['user', 'isActive']} label="激活" valuePropName="checked">
                                <Checkbox></Checkbox>
                            </Form.Item>
                            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>
                                <Button type="primary" htmlType="submit" loading={this.state.loading}>保存</Button>
                            </Form.Item>
                        </Form>
                    </Col>
                    <Col span={8}>
                        <p>头像</p>
                        <Upload
                            action={UploadUtil.actionURL}
                            headers={{
                                'Authorization': UploadUtil.accessToken,
                            }}
                            data={{
                                objectId: datas.id,
                                objectName: 'user',
                                objectField: 'avater'
                            }}
                            name="files"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            beforeUpload={UploadUtil.beforeUpload}
                            onChange={this.handleChange}
                        >
                            {imageUrl ? <img src={UploadUtil.imgServ + imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                        <Button onClick={() => this.setState({ visible4: true })} >选择图片</Button>
                        <Modal
                            title={<b>密码更改</b>}
                            visible={this.state.visible}
                            onOk={() => this.switchModal(false)}
                            onCancel={() => this.switchModal(false)}
                            footer={null}
                            destroyOnClose={true}>
                            <PswUpdate userId={this.state.datas.id} />
                        </Modal>
                    </Col>
                </Row>
                <Modal
                    title='图片选择'
                    visible={this.state.visible4}
                    destroyOnClose={true}
                    onCancel={() => this.setState({ visible4: false })}
                    width={750}
                    footer={false}
                >
                    <ImgQuick clickFun={(val: any) => this.clickFun(val)} ext='.jpg,.jpeg,.png,.gif' />
                </Modal>
            </div>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(UserEdit);